/**
 * 任务数据映射工具
 * 统一处理不同任务类型的数据字段映射
 */

// 统一的任务数据字段规范
export const TASK_FIELD_MAPPING = {
  // 基础信息
  ID: 'id',
  TITLE: 'title',
  DESCRIPTION: 'description',
  TYPE: 'type',
  STATUS: 'status',
  REWARD: 'reward',
  
  // 时间相关
  PUBLISH_TIME: 'publishTime',
  ACCEPT_TIME: 'acceptTime',
  COMPLETE_TIME: 'completeTime',
  EXPECTED_DELIVERY_TIME: 'expectedDeliveryTime', // 统一使用驼峰命名
  
  // 角色相关
  PUBLISHER_ID: 'publisherId',     // 发布者ID
  PUBLISHER_NAME: 'publisherName', // 发布者姓名
  PUBLISHER_AVATAR: 'publisherAvatar', // 发布者头像
  
  ACCEPTOR_ID: 'acceptorId',       // 接收者ID
  ACCEPTOR_NAME: 'acceptorName',   // 接收者姓名
  ACCEPTOR_AVATAR: 'acceptorAvatar', // 接收者头像
  
  // 联系信息
  CONTACT_INFO: 'contactInfo',
  
  // 其他
  IS_URGENT: 'isUrgent',
  TAGS: 'tags',
  PAYMENT_ID: 'paymentId',
  PAYMENT_AMOUNT: 'paymentAmount',
  PAYMENT_METHOD: 'paymentMethod'
};

// 不同任务类型的字段映射规则
export const TASK_TYPE_MAPPINGS = {
  // 快速发布任务（使用other类型）
  other: {
    expected_delivery_time: 'expectedDeliveryTime',
    publisher_id: 'publisherId',
    publisher_name: 'publisherName',
    publisher_avatar: 'publisherAvatar',
    contact_info: 'contactInfo',
    contact_name: 'contactName',
    contact_phone: 'contactPhone',
    is_urgent: 'isUrgent'
  },
  
  // 外卖任务
  takeout: {
    expected_time: 'expectedDeliveryTime',
    publisher_id: 'publisherId',
    publisher_name: 'publisherName',
    publisher_avatar: 'publisherAvatar',
    acceptor_id: 'acceptorId',
    acceptor_name: 'acceptorName',
    acceptor_avatar: 'acceptorAvatar'
  },
  
  // 配送任务
  delivery: {
    expected_time: 'expectedDeliveryTime',
    publisher_id: 'publisherId',
    publisher_name: 'publisherName',
    publisher_avatar: 'publisherAvatar',
    acceptor_id: 'acceptorId',
    acceptor_name: 'acceptorName',
    acceptor_avatar: 'acceptorAvatar'
  },
  
  // 其他任务类型
  other: {
    expected_delivery_time: 'expectedDeliveryTime',
    publisher_id: 'publisherId',
    publisher_name: 'publisherName',
    publisher_avatar: 'publisherAvatar',
    acceptor_id: 'acceptorId',
    acceptor_name: 'acceptorName',
    acceptor_avatar: 'acceptorAvatar'
  }
};

/**
 * 标准化任务数据
 * @param {Object} rawData - 原始任务数据
 * @param {String} taskType - 任务类型
 * @returns {Object} 标准化后的任务数据
 */
export function normalizeTaskData(rawData, taskType = 'other') {
  if (!rawData || typeof rawData !== 'object') {
    console.error('[数据标准化] 无效的原始数据:', rawData);
    return null;
  }

  const mapping = TASK_TYPE_MAPPINGS[taskType] || TASK_TYPE_MAPPINGS.other;
  const normalizedData = { ...rawData };

  // 应用字段映射
  Object.keys(mapping).forEach(oldKey => {
    const newKey = mapping[oldKey];
    if (rawData.hasOwnProperty(oldKey)) {
      normalizedData[newKey] = rawData[oldKey];
      // 保留原字段以避免破坏现有代码
      if (oldKey !== newKey) {
        normalizedData[oldKey] = rawData[oldKey];
      }
    }
  });

  // 数据验证和修复
  normalizedData.id = normalizedData.id || normalizedData._id;
  normalizedData.type = normalizedData.type || taskType;
  normalizedData.status = normalizedData.status || 'pending';
  
  console.log('[数据标准化] 任务类型:', taskType, '标准化后数据:', normalizedData);
  return normalizedData;
}

/**
 * 获取角色信息
 * @param {Object} taskData - 任务数据
 * @param {String} userId - 当前用户ID
 * @returns {Object} 角色信息 { role: 'publisher'|'acceptor'|'none', partner: {...} }
 */
export function getRoleInfo(taskData, userId) {
  if (!taskData || !userId) {
    console.error('[角色判断] 缺少必要参数:', { taskData, userId });
    return { role: 'none', partner: null };
  }

  const publisherId = taskData.publisherId || taskData.publisher_id;
  const acceptorId = taskData.acceptorId || taskData.acceptor_id || taskData.receiver_id;

  console.log('[角色判断] 用户ID:', userId);
  console.log('[角色判断] 发布者ID:', publisherId);
  console.log('[角色判断] 接收者ID:', acceptorId);

  let role = 'none';
  let partner = null;

  if (publisherId === userId) {
    role = 'publisher';
    partner = {
      id: acceptorId,
      name: taskData.acceptorName || taskData.acceptor_name || taskData.receiver_name || '任务接收者',
      avatar: taskData.acceptorAvatar || taskData.acceptor_avatar || taskData.receiver_avatar || '/static/images/default-avatar.png'
    };
  } else if (acceptorId === userId) {
    role = 'acceptor';
    partner = {
      id: publisherId,
      name: taskData.publisherName || taskData.publisher_name || '任务发布者',
      avatar: taskData.publisherAvatar || taskData.publisher_avatar || '/static/images/default-avatar.png'
    };
  }

  console.log('[角色判断] 最终角色:', role, '聊天对象:', partner);
  return { role, partner };
}

/**
 * 验证任务数据完整性
 * @param {Object} taskData - 任务数据
 * @returns {Object} 验证结果 { isValid: boolean, errors: string[] }
 */
export function validateTaskData(taskData) {
  const errors = [];
  
  if (!taskData) {
    errors.push('任务数据为空');
    return { isValid: false, errors };
  }

  // 必需字段检查
  const requiredFields = ['title', 'publisherId'];
  requiredFields.forEach(field => {
    if (!taskData[field]) {
      errors.push(`缺少必需字段: ${field}`);
    }
  });

  // ID字段检查（如果存在但为空则报错）
  if (taskData.hasOwnProperty('id') && !taskData.id) {
    errors.push('ID字段不能为空');
  }

  // 时间字段检查
  if (taskData.expectedDeliveryTime && !isValidDateTime(taskData.expectedDeliveryTime)) {
    errors.push('期望完成时间格式不正确');
  }

  // 角色字段检查
  if (taskData.publisherId && taskData.acceptorId && taskData.publisherId === taskData.acceptorId) {
    errors.push('发布者和接收者不能是同一人');
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * 验证日期时间格式
 * @param {String} dateTime - 日期时间字符串
 * @returns {Boolean} 是否有效
 */
function isValidDateTime(dateTime) {
  if (!dateTime) return false;
  
  // 支持相对时间格式（如"1小时内"、"2天内"等）
  const relativeTimePatterns = [
    /^\d+小时内$/,
    /^\d+天内$/,
    /^\d+周内$/,
    /^\d+月内$/
  ];
  
  // 检查是否为相对时间格式
  if (relativeTimePatterns.some(pattern => pattern.test(dateTime))) {
    return true;
  }
  
  // 检查是否为具体日期时间格式
  const date = new Date(dateTime);
  return !isNaN(date.getTime());
}

/**
 * 调试工具：打印任务数据映射信息
 * @param {Object} taskData - 任务数据
 * @param {String} context - 上下文信息
 */
export function debugTaskData(taskData, context = '') {
  console.group(`[调试] 任务数据映射 ${context}`);
  console.log('原始数据:', taskData);
  console.log('字段映射检查:');
  
  Object.keys(TASK_FIELD_MAPPING).forEach(key => {
    const field = TASK_FIELD_MAPPING[key];
    console.log(`${key} (${field}):`, taskData[field]);
  });
  
  console.groupEnd();
}